var _ljs=require("./mmlog").root("[sever/channelManager.js]");

var util = require("./util");
var config = require("./config");
var _session = require("./session");
var _dbCustomer = require("./db/customer");
var _message = require("./message");

var _avFormatter=require("./av-formatter.js");

function toSession(param, channel, callback) {
	var t = new Date().getTime();
	var _ = {
		sessionId: "",
		keyId: "",
		from: "",
		to: "",
		jobId: "",
		channel: channel,
		createTime: t,
		startTime: "",
		business: "0",
		customer:{
			id:"",
			name:"",
			email:"",
			mobile:"",
			lastTime:"",
			lastSession:"",
			address:"",
			count:0,
			createTime:""
		},
		lastMessage: {
			type: "text",
			content: "",
			sendTime: t
		},
		user: {
			name: "",
			image: ""
		},
		status: 0 //0 wait 1 dealing 2 done
	}

	if (config.vars.wechat == channel) {
		_.from = param.FromUserName;
		_.to = param.ToUserName;
		_.sessionId = util.sha1(util.arrayString([param.FromUserName, param.ToUserName, t]));
		_.keyId = util.sha1(util.arrayString([param.FromUserName, param.ToUserName]));
		_.business=param.EventKey.replace("AGENT_EVENT_","");
	}

	return _;
}

function toMessage(param, channel) {

	var _ = {
		messageId: util.rid(),
		sessionId: "",
		keyId: "",
		type: "",
		source: 0,
		content: "",
		sendTime:new Date().getTime()
	}

	if (config.vars.wechat == channel) {
		var _keyId = util.sha1(util.arrayString([param.FromUserName, param.ToUserName])),
			_s = _session.getSessionByKeyId(_keyId);
		_ljs.debug("消息keyId\n",_keyId);
		if (!_s) {
			return null;
		}
		_.keyId = _keyId;
		_.sessionId = _s.sessionId;
		_.user = _s.user;
		_.content = param.Content || param.PicUrl || param.MediaId;
		_.type = param.MsgType;
	}

	return _;

}

module.exports = {

	session: function(channel, param,callback) {
		var _ = toSession(param, channel),
			_cid="";
		_dbCustomer.selectIdByAccount([_.channel,_.from],function(data){
			var time=new Date().getTime();
			if(data && data.length && data[0].cid){
				_ljs.debug("客户识别:\n",data[0]);
				_d=data[0];
				_.customer.id=_d.cid;
				_.customer.name=_d.name||"";
				_.customer.createTime=_d.createTime||"";
				_.customer.lastTime=_d.lastTime||"";
				_.customer.email=_d.email||"";
				_.customer.count=_d.count||"";
				_.customer.mobile=_d.mobile||"";
				_.customer.address=_d.address||"";
				_.customer.lastSession=_d.lastSession||"";
			}else{
				_cid=util.rid(); 
				_dbCustomer.insertCustomer(_cid,time);
				_dbCustomer.insertCustomerAccoount(util.rid(),_cid,_.channel,_.from,time);
				_.customer.id=_cid;
				_.customer.createTime=time;
			}
			_ljs.debug("收到一个会话请求:\n", _);
			_session.acceptSession(_,callback);
		})
		
	},

	message: function(channel, param) {
		var _ = toMessage(param, channel);
		if(_){
			_ljs.info("人工消息:\n",_);
			if(_.content=="#"){
				_session.closeSession(_.keyId); 
				return true;
			}
			var _type=_.type;
			if(_type=="image"){
				util.qnUpload(_.content,function(v){
					_.content=v;
					_message.acceptMessage(_);
				});
			}else if(_type=="voice"){
				//微信媒体文件下载
				util.wxDown(_.content,function(name){
					//微信媒体文件格式转换
					_avFormatter.amr2mp3(name,"./temp/"+util.rid()+".mp3",function(error,file){
						if(!error){
							util.qnLocalUpload(file,function(error,url){
								if(!error){
									_.content=url;
									_message.acceptMessage(_);
								}
							})
						}
					})
				})
			}else{
				_message.acceptMessage(_);
			}
			return true;
		}
		_ljs.error("非人工消息、丢弃");
		return false;
	}

}